<template>
	<scroll-view class="page-content" :scroll-top="scrollTop" scroll-y="true">
		<!-- @scrolltolower="loadmore()" -->
		<view class="index-header">
			<!--导航-->
			<view class="nav">
				<view class="nav-item" @click="handleActive(1)"
					:class="[active === 1 ? 'active' : active === 2 ? '' : '']">
					我的用时
				</view>
				<view class="nav-item" @click="handleActive(2)"
					:class="[active === 1 ? '' : active === 2 ? 'active' : '']">
					队伍信息
				</view>
				<view class="nav-item" @click="handleActive(3)"
					:class="[active === 1 ? '' : active === 2 ? '' : 'active']">
					赛事详情
				</view>
			</view>
		</view>
		<view class="page-body">
			<!--队伍信息-->
			<view class="body-item1" v-if="active === 1">
				<view class="item-box">
					<view class="item-box-tit">所在队伍：{{objdata.teamname}}<text>（用时：{{objdata.time}}）</text></view>
					<view class="item-box-txt">队长：<text>{{objdata.name1}}</text></view>
					<view class="item-box-txt" v-if="objdata.name2.length>0">队员：
						<block v-for="(item,index) in objdata.name2" :key="index">
							<text v-if="objdata.name2.length===index+1">{{item.name}}</text>
							<text v-else>{{item.name}}、</text>
						</block>
					</view>
				</view>
				<view class="item-box3" @tap="handleShowPoster">
					<view class="user-info">
						<image class="user-head" :src="objdata.wechat_img"></image>
						<view class="user-name">{{objdata.name}}</view>
						<view class="user-txt" v-if="objdata.time !='未完成'">恭喜您完成了：{{objdata.game_title}}</view>
						<view class="user-txt" v-if="objdata.time ==='未完成'">参加了：{{objdata.game_title}}
						</view>
						<view class="user-txt" v-if="objdata.time!='未完成'">用时：{{objdata.time}}</view>
					</view>
					<image mode="widthFix" class="item-box-img" :src="objdata.base_img"></image>
				</view>
				<wPoster ref="wPoster" @cancel="canvasCancel" :attrs.sync="attrs"></wPoster>
				<!-- 富文本 -->
				<!-- <view class="item-box2" v-if="objdata.remarks != ''">
					<rich-text class="con-text" :nodes='objdata.remarks' decode='true'></rich-text>
				</view> -->

			</view>
			<!--队伍信息-->
			<view class="body-item" v-if="active === 2">
				<team-info isload="2" @toedit="toedit" @callpho="callpho" @recordid="recordid" :datalist="datalist1"
					@imgDelete="imgDelete" @ChooseSuccess="ChooseSuccess"></team-info>
			</view>

			<!--赛事详情-->
			<view class="body-item" v-if="active === 3">
				<entry-info :datalist="datalist2"></entry-info>
			</view>
		</view>
	</scroll-view>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex'
	import loadMore from "@/components/uni-load-more/load-more.vue";
	import wPoster from "@/components/w-poster/w-poster.vue"; //海报组件
	import entryInfo from "@/pages/user/components/entry_info.vue"; //赛事详情组件
	import teamInfo from "@/pages/user/components/team_info"; //赛事详情组件
	import {
		getGameTeamInfos, //获取赛事报名团队信息
		getgameinfos, //获取待开赛比赛详情
		upGameMapCoordImgs, //上传坐标点图片 
		getGameOverTimeDatas,
		getGameOverRemarks, //获取赛事详情富文本
	} from '@/common/api.js'

	export default {
		components: {
			entryInfo,
			teamInfo,
			loadMore,
			wPoster
		},
		data() {
			return {
				scrollTop: 0,
				load_sta: false, //是否是加载状态
				active: 1, //tab导航
				datalist1: {},
				datalist2: {},
				game_id: '', //赛事id传值
				coord_id: '', //坐标id
				team_id: '', //团队id
				formdata: {
					img: ''
				},
				img_box: {
					width: '',
					height: ''
				},
				objdata: {
					teamname: '',
					name: '',
					game_title: '',
					base_img: '',
					game_title: '',
					time: '',
					name1: '',
					name2: [],
					remarks: ''
				},
				posterObj: {},
				attrs: {
					marginLR: 15,
					marginTB: 30,
					radius: 0.01,
					fillColor: '#ffffff',
					innerLR: 20,
					innerTB: 20,
					posterRatio: 1,
					posterImgUrl: "",
					title: "",
					name: "",
					txt: "",
					time: "",
					titleFontSize: 13,
					titleLineHeight: 25,
					posterCodeUrl: "",
					codeWidth: 0.3,
					codeRatio: 1,
					codeRadius: 0.5,
					codeMT: 20,
					codeName: "记忆之王",
					codeNameMT: 20,
					tips: "长按/扫描识别查看商品",
					posterBgUrl: '',
					codeML: 140,
					desTextMT: 70,
					desTextML: 240,
				}
			}
		},
		computed: {
			...mapState(['hasLogin', 'openid', 'token', 'agent_id', 'userInfo'])
		},

		onShow() {
			this.getdata0();
			this.getdata1();
			this.getdata2();
		},
		onLoad(option) {
			console.log(222, option)
			if (option.id) {
				this.game_id = option.id
			}
			// #ifdef MP-WEIXIN
			wx.showShareMenu({
				withShareTicket: true,
				//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
				menus: ["shareAppMessage", "shareTimeline"]
			})
			//#endif
		},
		//发送给朋友
		onShareAppMessage(res) {
			// 此处的distSource为分享者的部分信息，需要传递给其他人
			let distSource = uni.getStorageSync('distSource');
			if (distSource) {
				return {
					title: '欢迎使用穿越小程序',
					type: 0,
					path: '/pages/index/match_detail?id=' + distSource,
					summary: "",
					imageUrl: ""
				}
			}
		},
		//分享到朋友圈
		onShareTimeline(res) {
			let distSource = uni.getStorageSync('distSource');
			if (distSource) {
				return {
					title: '欢迎使用穿越小程序',
					type: 0,
					query: 'id=' + distSource,
					summary: "",
					imageUrl: ""
				}
			}
		},
		methods: {
			//生成海报
			handleShowPoster() {
				let _self = this;
				if (this.objdata.base_img != '') {
					if (this.objdata.wechat_img != '') {
						this.attrs.posterBgUrl = this.objdata.base_img;
						this.attrs.posterImgUrl = this.objdata.wechat_img;
						this.attrs.name = this.objdata.name;
						this.attrs.txt = this.objdata.game_time === '未完成' ? '参加了：' + this.objdata
							.game_title : '恭喜您完成了：' + this.objdata.game_time;
						this.attrs.time = '用时：' + this.objdata.time;
						this.posterObj = this.attrs;
						this.$nextTick(() => {
							_self.$refs.wPoster.posterShow();
						});
					} else {
						uni.showToast({
							title: "用户头像下载异常，无法生成海报",
							duration: 2000,
							icon: "none"
						})
					}
				} else {
					uni.showToast({
						title: "海报背景图下载异常，无法生成海报",
						duration: 2000,
						icon: "none"
					})
				}
			},

			//取消海报
			canvasCancel(val) {

			},

			change(e) {},
			recordid(id) {
				if (this.datalist1.sign_data && this.datalist1.sign_data.length > 0) {
					this.datalist1.sign_data.forEach(item => {
						if (item.id === id) {
							this.coord_id = item.id;
						}
					})
				}
				this.team_id = this.datalist1.id;
			},
			imgDelete(row) {
				let _self = this;
				/* let get_data = '?game_id=' + _self.game_id +'&team_id='+ _self.team_id +'&coord_id='+ _self.coord_id
				upGameMapCoordImgs(get_data).then(res =>{
					
				}) */
			},
			ChooseSuccess(tempFilePaths) { //选择图片返回
				this.imgUpload(tempFilePaths);
			},
			imgUpload(tempFilePaths) {
				let _self = this;
				uni.showLoading({
					title: '上传中'
				});
				let uploadImgs = [];
				tempFilePaths.forEach((item, index) => {
					uploadImgs.push(new Promise((resolve, reject) => {
						let str = 'blob:http://localhost:8080/';
						let imgName = '';
						if (item.indexOf(str) > -1) {
							imgName = item.split("blob:http://localhost:8080/")[1]
						} else {
							imgName = item
						}
						//上传图片接口
						uni.uploadFile({
							url: 'http://cys.swy666.cn/api/upGameMapCoordImg?game_id=' + _self
								.game_id + '&team_id=' + _self.team_id + '&coord_id=' + _self
								.coord_id + '&openid=' + _self.openid,
							formData: {
								key: imgName + '.jpg',
								fname: imgName + '.jpg',
							},
							filePath: item,
							name: 'file',
							success: (uploadFileRes) => {
								resolve(uploadFileRes);
								let _res = JSON.parse(uploadFileRes.data);
								if (_self.datalist1.sign_data && _self.datalist1.sign_data
									.length > 0) {
									_self.datalist1.sign_data.forEach(item => {
										let check_img = []
										if (item.id === _self.coord_id) {
											check_img.push(_res.data.img)
											item.check_img = check_img;
										}
									})
								}
							},
							fail: (err) => {
								console.log(err);
								reject(err);
							},
							complete: () => {
								//uni.hideLoading();
							}
						});
					}))
				})
				Promise.all(uploadImgs).then((results) => { //执行所有需请求的接口
						uni.hideLoading();
					})
					.catch((res, object) => {
						uni.hideLoading();
					});
			},
			//打电话
			callpho(pho) {
				uni.makePhoneCall({
					phoneNumber: pho
				});
			},
			toedit(id) {
				uni.navigateTo({
					url: '/pages/user/entryEdit?team_id=' + id + '&game_id=' + this.game_id
				})
			},
			//获取当前比赛数据
			getdata0() {
				let _self = this;
				getGameOverTimeDatas({
					game_id: this.game_id
				}).then(res => {
					if (res.code === 2000) {
						this.objdata.teamname = res.data.title;
						this.objdata.time = res.data.game_time;
						this.objdata.base_img = res.data.base_img.replace(/[\r\n]/g, '');
						this.objdata.wechat_img = res.data.wechat_img;
						this.objdata.game_time = res.data.game_time;
						this.objdata.game_title = res.data.game_title;
						this.objdata.name = res.data.my_data.name;

						let name = [];
						res.data.user_data.forEach(item => {
							if (item.type === 1) {
								this.objdata.name1 = item.name;
							}
							if (item.type === 2) {
								name.push(item)
							}
						})
						this.objdata.name2 = name;
						/* getGameOverRemarks({
							id: this.game_id
						}).then(res2 => {
							if (res2.code === 2000) {
								this.objdata.remarks = this.formatRichText(res2.data.data)
							} else {
								uni.showToast({
									title: res2.msg,
									icon: 'none',
									duration: 2000
								})
							}
						}) */
					}
				})
			},
			//获取当前比赛数据
			getdata1() {
				getGameTeamInfos({
					game_id: this.game_id
				}).then(res => {
					if (res.code === 2000) {
						this.datalist1 = res.data;
						this.datalist1.clock_qr_img = res.data.clock_qr_img;
						if (this.datalist1.sign_data && this.datalist1.sign_data.length > 0) {
							this.datalist1.sign_data.forEach(item => {
								this.$set(item, 'check_img', Array);
								let check_img = [];
								if (item.img != '') {
									check_img.push(item.img);
									item.check_img = check_img;
								}
							})
						}
					}
				})
			},
			//赛事详情
			getdata2() {
				getgameinfos({
					id: this.game_id
				}).then(res => {
					if (res.code === 2000) {
						this.datalist2 = res.data;
						this.datalist2.onload_img = res.data.game_img[0];
						this.datalist2.signsta = res.data.status;
						this.datalist2.signtime = res.data.sign_start_time.replace(/-/g, '/') + ' - ' + res.data
							.sign_end_time.replace(/-/g, '/');
						this.datalist2.game_start_time = res.data.game_start_time.replace(/-/g, '/');
						this.datalist2.remarks = this.formatRichText(res.data.remark);
					}
				})
			},
			change(e) {
				this.current = e.detail.current
			},
			handleActive(e) {
				let _self = this;
				_self.active = e;
				_self.load_sta = false;
				if (_self.active === 1) {
					_self.getdata0();
				}
				if (_self.active === 2) {
					_self.getdata1();
				}
				if (_self.active === 3) {
					_self.getdata2();
				}
			},
			//跳转比赛详情
			clickdet(type, item) {
				uni.navigateTo({
					url: `/pages/index/race_detail?type=${type}&data=${JSON.stringify(item)}`
				})
			},
			formatRichText(html) {
				let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
					match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
					match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
					match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
					return match;
				});
				newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
					match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
						'max-width:100%;');
					return match;
				});
				newContent = newContent.replace(/<br[^>]*\/>/gi, '');
				newContent = newContent.replace(/\<img/gi,
					'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
				return newContent;
			},
		},
		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		}
	}
</script>

<style lang="scss">
	.page-content {
		height: 100vh;
		width: 100vw;
	}

	.det-con-more {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 10rpx;
		color: #bbb;
		font-size: 24rpx;
	}

	.index-header {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 70rpx;
		background-color: #f5f5f5;
		position: relative;

		.nav {
			height: 100rpx;
			padding: 0 30rpx;
			display: flex;
			align-items: center;
			text-align: center;
			font-size: 28rpx;
			color: #999;

			.nav-item {
				flex: 1;
				position: relative;

				&::after {
					content: '';
					width: 0;
					height: 8rpx;
					background-color: #02BB6F;
					border-radius: 4px;
					position: absolute;
					left: 50%;
					bottom: -12rpx;
					transform: translateX(-50%);
					transition: .3s;
				}

				&.active {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;

					&::after {
						width: 60rpx;
					}
				}
			}
		}
	}

	.page-body {
		height: calc(100% - 70rpx);
		background-color: #f5f5f5;

		.body-item {
			margin: 20rpx 0;
			height: 100%;
		}

		.body-item1 {
			margin: 20rpx 0;
			height: 100%;

			.item-box {
				margin: 0 30rpx 30rpx 30rpx;
				padding: 20rpx 30rpx;
				line-height: 50rpx;
				color: #fff;
				font-size: 28rpx;
				border-radius: 10rpx;
				background: #02BB6F;
			}

			.item-box2 {
				margin: 0 30rpx;
				padding: 20rpx 30rpx;
				line-height: 50rpx;
				color: #fff;
				font-size: 28rpx;
				border-radius: 10rpx;
				background: #fff;

				.con-text {
					width: 100%;
					display: flex;
					flex-direction: column;
					font-size: 28rpx;
					color: #666;
					line-height: 40rpx;

					image {
						width: 100% !important;
						max-width: 100% !important;
					}
				}
			}

			.item-box3 {
				margin: 0 30rpx;
				line-height: 40rpx;
				color: #fff;
				font-size: 28rpx;
				border-radius: 10rpx;
				background: #d3d3d3;
				min-height: 300rpx;
				position: relative;
				overflow: hidden;

				.user-info {
					display: flex;
					flex-direction: column;
					position: absolute;
					left: 60rpx;
					top: 20rpx;

					.user-head {
						width: 150rpx;
						height: 150rpx;
						margin-bottom: 20rpx;
						border-radius: 50%;
					}
				}

				.item-box-img {
					width: 100%;
				}

			}
		}
	}

	.canvas {
		position: fixed !important;
		top: 0 !important;
		left: 0 !important;
		display: block !important;
		width: 100% !important;
		height: 100% !important;
		z-index: 10;
	}
</style>
